package com.wzq.controller;

import com.wzq.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wzq.Jolin
 * @company none
 * @create 2020-09-14 11:48
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 注册
     * @param email
     * @param password
     * @param code
     * @return
     */
    @RequestMapping("/user/register/{email}/{password}/{code}")
    public boolean register(@PathVariable String email,
                            @PathVariable String password,
                            @PathVariable String code){
        return userService.register(email,password,code);
    }

    /**
     * 校验是否已注册
     * @param email
     * @return
     */
    @RequestMapping("/user/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email){
        return userService.isRegistered(email);
    }

    /**
     * 登录
     * @param email
     * @param password
     * @return token
     */
    @RequestMapping("/user/login/{email}/{password}")
    public boolean login(HttpServletResponse response,
                         @PathVariable String email,
                         @PathVariable String password){
        String token = userService.login(email,password);

        //放入cookie
        Cookie cookie = new Cookie("wzq_token", token);
//        cookie.setHttpOnly(false);
//        cookie.setMaxAge(-1);
//        cookie.setDomain("localhost");
        cookie.setValue( token );
        cookie.setPath("/");
        response.addCookie(cookie);
//        response.addHeader("P3P", "CP=CAO PSA OUR");

        return StringUtils.isNotBlank(token);
    }

    /**
     * 获取登录的邮箱
     * @param request
     * @return
     */
    @RequestMapping("/user/info")
    public String info(HttpServletRequest request){
        String token = "";
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            if("wzq_token".equals(cookie.getName())){
                token = cookie.getValue();
                break;
            }
        }

        return userService.info(token);
    }

    @GetMapping("/user/logout")
    public void logout(HttpServletResponse response) {

        response.addHeader("auth", "");
    }
}
